package managers

import (
	"context"

	"dev.ixmxm.top/rms/codes"
	"dev.ixmxm.top/rms/managers/chargemanager"
	"dev.ixmxm.top/rms/managers/devicemanager"
	"dev.ixmxm.top/rms/managers/locationmanager"
	"dev.ixmxm.top/rms/managers/logmanager"
	resourecemanager "dev.ixmxm.top/rms/managers/resourcemanager"
	"dev.ixmxm.top/rms/managers/robotmanager"
	"dev.ixmxm.top/rms/managers/taskmanager"
	"dev.ixmxm.top/rms/managers/templatemanager"
	"dev.ixmxm.top/rms/managers/trafficmanager"

	//"dev.ixmxm.top/rms/managers/usermanager"

	"dev.ixmxm.top/rms/managers/usermanager"
	"dev.ixmxm.top/rms/model"
	"dev.ixmxm.top/rms/utils/log"
	"dev.ixmxm.top/rms/utils/tools"
)

type ManagerCluster struct {
	TM  *taskmanager.TaskManager          //任务对象
	TRM *trafficmanager.TrafficManager    //交通管理对象
	CM  *chargemanager.ChargeManager      //充电桩对象
	LM  *logmanager.LogManager            //日志对象
	DM  *devicemanager.DeviceManager      //设备对象
	TTM *templatemanager.TemplateManager  //任务模板对象
	RSM *resourecemanager.ResourceManager //资源管理
	WMM *locationmanager.LocationManager  //库位管理

	UM *usermanager.UserManager
}

func (mc *ManagerCluster) MakePlanRejectNodes(agvID, mapName string, cover_node []string, currentSubTask *model.Subtask) (globalRejects map[string]string, globalRejectsAll map[string]string, localRejects map[string]string) {
	//全局路径剔除点与局部路径剔除点
	//全局路径剔除锁定站点,停止的机器人站位点,运行中任务的终点
	//局部路径剔除机器人站位点、锁定站点
	selfNode := make(map[string]string, 0)
	for _, cover := range cover_node {
		coverNode := mc.TRM.GetNode(mapName, cover)
		selfNode[cover] = cover
		for _, ass := range coverNode.AssociatedBlocks {
			selfNode[ass] = ass
		}
	}

	globalRejects = make(map[string]string, 0)
	globalRejectsAll = make(map[string]string, 0)
	localRejects = make(map[string]string, 0)
	addGlobalRejects := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		globalRejects[id] = id
	}
	addGlobalRejectsAll := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		globalRejectsAll[id] = id
	}
	addLocalRejects := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		localRejects[id] = id
		node := mc.TRM.GetNode(mapName, id)
		for _, a := range node.AssociatedBlocks {
			localRejects[a] = a
		}
	}
	getMapSitesInMapRelations := func(relations []model.MapRelation, mapName, nodeMap, node string) []string {
		mapSites := make([]string, 0)
		for _, relation := range relations {
			if relation.GoalId == node && relation.ToMap == nodeMap && relation.FromMap == mapName {
				mapSites = append(mapSites, relation.StartId)
			} else if relation.StartId == node && relation.FromMap == nodeMap && relation.ToMap == mapName {
				mapSites = append(mapSites, relation.GoalId)
			}
		}
		return mapSites
	}
	mapRelations, _ := mc.TRM.GetAllMapRelationFromDB(context.TODO())
	for _, mapRelation := range mapRelations {
		if mapRelation.AgvId != "" && mapRelation.AgvId != agvID {
			if mapRelation.FromMap == mapName {
				addGlobalRejectsAll(mapRelation.StartId)
			} else if mapRelation.ToMap == mapName {
				addGlobalRejectsAll(mapRelation.GoalId)
			}
		}
	}
	for _, robot := range robotmanager.GetAllFromCache() {
		if !robot.StatusIsExists() {
			if robot.Account.MapName == mapName {
				ids := robotmanager.GetLocalSitesFromDB(context.Background(), robot.Account.AgvId)
				for _, site := range ids {
					addGlobalRejectsAll(site)
				}
			}
			continue
		}
		if robot.Status.AgvId == agvID || robot.Status.MapName != mapName || !mc.TRM.MapNameExists(robot.Status.MapName) {
			continue
		}
		node := mc.TRM.GetNode(robot.Status.MapName, robot.Status.SiteIdS)
		if node.Type == model.NodeElevator || node.Type == model.NodeSwitch {
			mapSites := getMapSitesInMapRelations(mapRelations, mapName, robot.Status.MapName, node.Id)
			for _, site := range mapSites {
				addGlobalRejectsAll(site)
			}
		} else {
			for _, cover := range robot.AgvCorverNodes {
				if cover == "" {
					continue
				}
				coverNode := mc.TRM.GetNode(robot.Status.MapName, cover)
				if coverNode.Type == model.NodeElevator || coverNode.Type == model.NodeSwitch {
					mapSites := getMapSitesInMapRelations(mapRelations, mapName, robot.Status.MapName, coverNode.Id)
					for _, site := range mapSites {
						addGlobalRejectsAll(site)
					}
					break
				}
			}
		}
		addLocalRejects(robot.Status.SiteIdS)
		for _, id := range robot.AgvCorverNodes {
			if id != "0" {
				addLocalRejects(id)
			}
		}

		if (node.Type == model.NodeStation && node.LocationType != model.LocationGround) || node.Type == model.NodeAvoid || node.Type == model.NodeCharge {
			for _, ban := range node.BanNodes {
				//log.Infof("无法到达:%d,绑定站点:%d有机器人停留", ban, node.Id)
				addGlobalRejectsAll(ban)
			}
			for _, id := range robot.AgvCorverNodes {
				if id != "0" {
					addGlobalRejectsAll(id)
				}
			}
		}
		switch robot.Status.Status {
		case model.RobotStatusNavigating, model.RobotStatusExecStandby:
			continue
		default:
			//todo 终点问题，是否要提前过去
			// log.Infof("robot:%s无法到达:%d,有机器人停留", robot.Account.AgvId, node.Id)
			if mc.TRM.SystemConfig.TrafficCfg.UseAvoidOtherAgvs && !mc.TRM.SystemConfig.TrafficCfg.UseIdleAvoid {
				addGlobalRejectsAll(robot.Status.SiteIdS)
			}
		}
		if robot.Status.ControlType == 0 || !robot.TaskOnline {
			ids := robotmanager.GetLocalSitesFromDB(context.Background(), robot.Account.AgvId)
			for _, site := range ids {
				addGlobalRejectsAll(site)
			}
			continue
		}
	}

	tasks, errGetTasks := mc.TM.GetAllStatusOrCurrentTaskFromDB(context.Background(), model.TaskRunningStatus(), currentSubTask)
	if errGetTasks != nil {
		log.Panicf("get all running tasks error:%v", errGetTasks)
	}

	//考虑任务时间，优先下发的任务优先完成，后发的任务只能中转或者避让等待
	// haveTask := false
	// taskStartTime := time.Now()
	// for _, t1 := range tasks {
	// 	if t1.AgvId == "" {
	// 		continue
	// 	}

	// 	if t1.Type == model.TaskTypeCharge {
	// 		continue
	// 	}
	// 	if t1.AgvId == agvID {
	// 		//--------------------严格时间顺序-------------------
	// 		//判断该目标点是否是严格按照顺序
	// 		node1 := mc.TRM.GetNode(t1.MapName, t1.TargetSiteID)
	// 		//判断node1是否需要严格按照顺序
	// 		if node1.Reserve2 == "1" {
	// 			//查询创建的更早时间还没完成的RMS任务
	// 			findTask, errGetTask := mc.TM.GetUnFinishedTaskByLocationInfoFromDB(context.Background(), *t1)
	// 			//有的话剔除目标点
	// 			if errGetTask != nil {
	// 				log.Panicf("get all unfinish task by locationInfo error:%v", errGetTasks)
	// 			}

	// 			if findTask != nil {
	// 				log.Warnf("当前任务Id：%d,存在更早的相同库位的任务:%+v", t1.Id, findTask)
	// 				addGlobalRejectsAll(node1.Id)
	// 				for _, ban := range node1.BanNodes {
	// 					addGlobalRejectsAll(ban)
	// 				}
	// 			}
	// 		}
	// 		//-------------------放货时间顺序---------------------
	// 		if t1.Type == model.TaskTypePut && t1.DependExternalTaskCode != "" {
	// 			//查看依赖的任务是否已经结束
	// 			//判断依赖任务是否已经结束
	// 			dependTask, errDependTask := mc.TM.GetDependExternalUnfinishTask(context.Background(), t1.DependExternalTaskCode)
	// 			if errDependTask != nil {
	// 				log.Panicf("get depend task :%d error:%s", t1.Id, errDependTask.Error())
	// 			}
	// 			if dependTask != nil {
	// 				log.Warnf("当前任务:%d ,依赖的任务:%d 还未结束，只能剔除当前目标点！！！", t1.Id, dependTask.Id)
	// 				addGlobalRejectsAll(node1.Id)
	// 				for _, ban := range node1.BanNodes {
	// 					addGlobalRejectsAll(ban)
	// 				}
	// 			}
	// 		}
	// 		//按照目标点ID找出
	// 		haveTask = true
	// 		taskStartTime = t1.CreatedTime
	// 		break
	// 	}
	// }

	for _, t := range tasks {
		if t.AgvId == agvID {
			continue
		}
		if t.Type == model.TaskTypeCharge && t.MapName == mapName {
			temp_node := mc.TRM.GetNode(t.MapName, t.TargetSiteID) //只要有充电任务存在，绑定站点都需要剔除，防止对应位置的待命点被批复
			for _, ban := range temp_node.BanNodes {
				addGlobalRejects(ban)
			}
		}
		//判断任务时间
		// if haveTask && t.CreatedTime.Sub(taskStartTime) > 0 {
		// 	// log.Infof("task%d的创建时间晚于 robot%s当前任务，不处理", t.Id, agvID)
		// 	continue
		// }

		subtask, _ := mc.TM.GetRunningSubtaskFromDB(context.Background(), t.AgvId)
		if subtask != nil {
			if subtask.MapName != mapName {
				continue
			}
			// if subtask.CheckFlg != 0 {
			// 	continue
			// }
			if t.Status == model.TaskStasusAvoid {
				if subtask.SubStatus == model.WalkToTargetReplace || subtask.SubStatus == model.WalkToTempReplace || subtask.SubStatus == model.WalkTempFinish {
					addGlobalRejectsAll(subtask.TempTargetSite)
					temp_node := mc.TRM.GetNode(subtask.MapName, subtask.TempTargetSite)
					for _, ban := range temp_node.BanNodes {
						addGlobalRejectsAll(ban)
					}
				} else if subtask.SubStatus == model.WalkNearAvoid || subtask.SubStatus == model.WalkAvoidFinish {
					addGlobalRejectsAll(subtask.AvoidSite)
					temp_node := mc.TRM.GetNode(subtask.MapName, subtask.AvoidSite)
					for _, ban := range temp_node.BanNodes {
						addGlobalRejectsAll(ban)
					}
				}
				continue
			} else if t.Status == model.TaskStatusInTheTransit {
				node := mc.TRM.GetNode(subtask.MapName, subtask.TargetSiteID)
				if node.Type == model.NodeStation && node.LocationType == model.LocationGround {
					continue
				}
				tmp := mc.TRM.GetNode(t.MapName, node.IntermediateNode)
				cnt := len(mc.TRM.GetPathPlanner(subtask.MapName).GetConnectPathsInStart(tmp))
				if cnt <= 1 {
					addGlobalRejectsAll(node.IntermediateNode) //正在执行任务的站点不发送任务（全局路径无法规划）
				}
				continue
			}
			node := mc.TRM.GetNode(subtask.MapName, subtask.TargetSiteID)
			// if node.Type != model.NodePath {
			if subtask.CheckFlg == 0 {
				addGlobalRejectsAll(subtask.TargetSiteID) //正在执行任务的站点不发送任务（全局路径无法规划）
			}
			for _, ban := range node.BanNodes {
				addGlobalRejectsAll(ban)
			}
			// }
		} else {
			nextSubtask, _ := mc.TM.GetWaitingSubtaskFromDB(context.Background(), t.AgvId)
			if nextSubtask != nil {
				if nextSubtask.MapName != mapName {
					continue
				}
				if nextSubtask.SwitchType == model.FactoryRealtion || nextSubtask.SwitchType == model.FloorRelation {
					addGlobalRejectsAll(nextSubtask.SwitchToSite)
				}
			}
		}

		if t.MapName != mapName {
			continue
		}
		node := mc.TRM.GetNode(t.MapName, t.TargetSiteID)
		if t.Status == model.TaskStatusInTheTransit {
			tmp := mc.TRM.GetNode(t.MapName, node.IntermediateNode)
			cnt := len(mc.TRM.GetPathPlanner(t.MapName).GetConnectPathsInStart(tmp))
			if cnt <= 1 {
				addGlobalRejectsAll(node.IntermediateNode) //正在执行任务的站点不发送任务（全局路径无法规划）
			}
		} else {
			addGlobalRejectsAll(t.TargetSiteID) //正在执行任务的站点不发送任务（全局路径无法规划）
			for _, ban := range node.BanNodes {
				addGlobalRejectsAll(ban)
			}
		}
	}
	planner := mc.TRM.GetPathPlanner(mapName)
	if planner == nil {
		log.Panic("get locked site error,can not get planner:")
	}

	//添加手动锁定剔除点--锁定点和锁定区域
	sites, err := mc.TRM.GetMapLockSiteFromDB(context.Background(), mapName)
	if err != nil {
		log.Panic("get locked site error:", err.Error())
	}
	for _, s := range sites {
		// log.Infof("无法到达:%d,该点为锁定站点", s.SiteId)
		globalRejects[s.SiteId] = s.SiteId
		globalRejectsAll[s.SiteId] = s.SiteId
	}
	areas, err := mc.TRM.GetMapLockAreaFromDB(context.Background(), mapName)
	if err != nil {
		log.Panic("get locked areas error:", err.Error())
	}
	for _, area := range areas {
		//当前的主任无编号和区域绑定的主任务一致
		bindMainTaskCode := ""
		if currentSubTask != nil {
			bindMainTaskCode = currentSubTask.MainTaskCode
			if area.MainTaskCode != "" && bindMainTaskCode != "" && bindMainTaskCode == area.MainTaskCode {
				log.Warnf("------该第三方交互区域：%d 将对于主任无编号：%s 无效", area.AreaId, area.MainTaskCode)
				continue
			}
		}
		// log.Infof("无法到达:%d,该点为锁定站点", s.SiteId)
		for _, siteId := range area.ContainDotIds {
			addGlobalRejects(siteId)
			addGlobalRejectsAll(siteId)
			addLocalRejects(siteId)
		}
	}

	for _, area := range planner.GetMap().MapData.Areas {
		if area.Type == model.AreaTypeBan && len(area.ContainDotIds) > 0 {
			for _, ban_agv := range area.BanAgvIds {
				if ban_agv == agvID {
					for _, dotId := range area.ContainDotIds {
						globalRejects[dotId] = dotId
						globalRejectsAll[dotId] = dotId
						addLocalRejects(dotId)
					}
					break
				}
			}
		}
	}
	//获得当前地图的门区域
	doorAreas := planner.GetAreaByAreaType(model.AreaTypeDoorArea)
	if len(doorAreas) > 0 {
		for _, doorArea := range doorAreas {
			//门区域
			for _, pointId := range doorArea.ContainDotIds {
				delete(globalRejectsAll, pointId)
			}
		}
	}
	//todo 关联节点
	return
}

func (mc *ManagerCluster) MakePlanRejectNodes1(agvID, mapName string, cover_node []string, currentAgvSite string) (globalRejects map[string]string, globalRejectsAll map[string]string, localRejects map[string]string, freeAvoidRejects map[string]string) {
	//全局路径剔除点与局部路径剔除点
	//全局路径剔除锁定站点,停止的机器人站位点,运行中任务的终点
	//局部路径剔除机器人站位点、锁定站点
	selfNode := make(map[string]string, 0)
	for _, cover := range cover_node {
		coverNode := mc.TRM.GetNode(mapName, cover)
		selfNode[cover] = cover
		for _, ass := range coverNode.AssociatedBlocks {
			selfNode[ass] = ass
		}
	}

	globalRejects = make(map[string]string, 0)
	globalRejectsAll = make(map[string]string, 0)
	localRejects = make(map[string]string, 0)
	freeAvoidRejects = make(map[string]string, 0)
	addGlobalRejects := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		globalRejects[id] = id
	}
	addGlobalRejectsAll := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		globalRejectsAll[id] = id
	}
	addLocalRejects := func(id string) {
		if _, find := selfNode[id]; find {
			return
		}
		localRejects[id] = id
		node := mc.TRM.GetNode(mapName, id)
		for _, a := range node.AssociatedBlocks {
			localRejects[a] = a
		}
	}

	for _, robot := range robotmanager.GetAllFromCache() {
		if !robot.StatusIsExists() {
			continue
		}
		if robot.Account.AgvId == agvID || robot.Account.MapName != mapName || !mc.TRM.MapNameExists(robot.Status.MapName) {
			continue
		}
		if !robotmanager.IsAgvHaveTask(context.Background(), robot.Account.AgvId) {
			continue
		}
		node := mc.TRM.GetNode(robot.Account.MapName, robot.Status.SiteIdS)
		addLocalRejects(robot.Status.SiteIdS)
		for _, id := range robot.AgvCorverNodes {
			if id != "0" {
				addLocalRejects(id)
			}
		}

		if robot.Status.Status != model.RobotStatusIdle {
			for _, ban := range node.BanNodes {
				//log.Infof("无法到达:%d,绑定站点:%d有机器人停留", ban, node.Id)
				addGlobalRejectsAll(ban)
			}
			for _, id := range robot.AgvCorverNodes {
				if id != "0" {
					addGlobalRejectsAll(id)
				}
			}
		} else {
			subtask, _ := mc.TM.GetRunningSubtaskFromDB(context.Background(), robot.Account.AgvId)
			if subtask != nil {
				if subtask.MapName != mapName {
					continue
				}
				for _, ban := range node.BanNodes {
					addGlobalRejects(ban)
					addGlobalRejectsAll(ban)
				}
				for _, id := range robot.AgvCorverNodes {
					if id != "0" {
						addGlobalRejects(id)
						addGlobalRejectsAll(id)
					}
				}
			}
		}

	}

	planner := mc.TRM.GetPathPlanner(mapName)
	if planner == nil {
		log.Panic("get locked site error,can not get planner:")
	}

	//添加手动锁定剔除点--锁定点和锁定区域
	sites, err := mc.TRM.GetMapLockSiteFromDB(context.Background(), mapName)
	if err != nil {
		log.Panic("get locked site error:", err.Error())
	}
	for _, s := range sites {
		globalRejects[s.SiteId] = s.SiteId
		globalRejectsAll[s.SiteId] = s.SiteId
		localRejects[s.SiteId] = s.SiteId
	}
	areas, err := mc.TRM.GetMapLockAreaFromDB(context.Background(), mapName)
	if err != nil {
		log.Panic("get locked areas error:", err.Error())
	}
	//找到当前AGV绑定的主任务编号
	bindMainTask, errb := mc.TM.GetMainTaskByAgvFromDB(context.Background(), agvID)
	if errb != nil {
		log.Panic("查询绑定主任务编号失败！！", agvID)
	}
	for _, area := range areas {
		//当前的主任无编号和区域绑定的主任务一致
		if bindMainTask != nil && area.MainTaskCode != "" && bindMainTask.MainTaskCode != "" && area.MainTaskCode == bindMainTask.MainTaskCode {
			continue
		}
		for _, siteId := range area.ContainDotIds {
			addGlobalRejects(siteId)
			addGlobalRejectsAll(siteId)
			addLocalRejects(siteId)
		}
	}

	//空闲避让----------------------------------------过滤点
	currentPlaner := mc.TRM.GetPathPlanner(mapName)
	if currentPlaner != nil {
		//当前互斥区域
		mutexAreas := currentPlaner.GetCurrentSiteIdArea(currentAgvSite, model.AreaTypeMutex)
		for _, mutexArea := range mutexAreas {
			for _, siteId2 := range mutexArea.ContainDotIds {
				freeAvoidRejects[siteId2] = siteId2
			}
		}
		//允许路线对冲区域
		allowPathMutexAreas := currentPlaner.GetAreaByAreaType(model.AreaTypeAllowPathMutex)
		for _, allowPathMutexArea := range allowPathMutexAreas {
			for _, siteId3 := range allowPathMutexArea.ContainDotIds {
				freeAvoidRejects[siteId3] = siteId3

			}
		}
		//潮汐区域
		tideAreas := currentPlaner.GetAreaByAreaType(model.AreaTypeTide)
		for _, tideArea := range tideAreas {
			for _, siteId4 := range tideArea.ContainDotIds {
				freeAvoidRejects[siteId4] = siteId4

			}
		}
		//禁停区域
		noParkingAreas := currentPlaner.GetAreaByAreaType(model.AreaTypeNoParkingArea)
		for _, noParkingArea := range noParkingAreas {
			for _, siteId5 := range noParkingArea.ContainDotIds {
				freeAvoidRejects[siteId5] = siteId5
			}
		}
		//门区域禁止空闲避让
		doorApplyAreas := currentPlaner.GetAreaByAreaType(model.AreaTypeDoorArea)
		for _, doorArea := range doorApplyAreas {
			for _, siteId6 := range doorArea.ContainDotIds {
				freeAvoidRejects[siteId6] = siteId6
			}
		}
	}

	for _, area := range planner.GetMap().MapData.Areas {
		if area.Type == model.AreaTypeBan && len(area.ContainDotIds) > 0 {
			for _, ban_agv := range area.BanAgvIds {
				if ban_agv == agvID {
					for _, dotId := range area.ContainDotIds {
						globalRejects[dotId] = dotId
						globalRejectsAll[dotId] = dotId
						addLocalRejects(dotId)
					}
					break
				}
			}
		}
	}
	return
}

func (mc *ManagerCluster) TargetPlanRejectNodes(agvID, mapName string) (targetRejects map[string]string) {

	planner := mc.TRM.GetPathPlanner(mapName)
	if planner == nil {
		log.Panic("get locked site error,can not get planner:")
	}
	targetRejects = make(map[string]string, 0)
	//添加手动锁定剔除点--锁定点和锁定区域
	sites, err := mc.TRM.GetMapLockSiteFromDB(context.Background(), mapName)
	if err != nil {
		log.Panic("get locked site error:", err.Error())
	}
	for _, s := range sites {
		// log.Infof("无法到达:%d,该点为锁定站点", s.SiteId)
		targetRejects[s.SiteId] = s.SiteId
	}

	for _, area := range planner.GetMap().MapData.Areas {
		if area.Type == model.AreaTypeBan && len(area.ContainDotIds) > 0 {
			for _, ban_agv := range area.BanAgvIds {
				if ban_agv == agvID {
					for _, dotId := range area.ContainDotIds {
						targetRejects[dotId] = dotId
					}
					break
				}
			}
		}
	}
	return

}

//任务限定区域按照类型区分
func (mc *ManagerCluster) GetRobotInLimitetAreaByGroupList(groupList []string, currentTask model.Task) (codes.Code, *model.Robot) {
	robotInArea := func(ids, ContainDotIds []string) bool {
		for _, id := range ContainDotIds {
			for _, myid := range ids {
				if id == myid {
					return true
				}
			}
		}
		return false
	}
	mapName := currentTask.MapName
	//1.先判断当前任务目标点是否在任务限定区域或者区域的前瞻点中
	currentPlaner := mc.TRM.GetPathPlanner(mapName)
	if currentPlaner == nil {
		return codes.ErrMapPlanerNotFound, nil
	}
	//存在规划器，找出当前目标点所在的限定区域
	limitTaskRobotAreas := currentPlaner.GetCurrentSiteIdContaintFrontArea(currentTask.TargetSiteID, model.AreaTypeTaskLimitRobotArea)
	if limitTaskRobotAreas == nil || len(limitTaskRobotAreas) <= 0 {
		return nil, nil
	}

	//目前只要按照一个区域来算
	limitArea := limitTaskRobotAreas[0]
	limitRobotAreaContains := limitArea.ContainDotIds
	if limitArea.FrontLookPoints != nil && len(limitArea.FrontLookPoints) > 0 {
		limitRobotAreaContains = append(limitRobotAreaContains, limitArea.FrontLookPoints...)
	}
	// //获得当前所有的局部路径
	// allApprovedLocalPath1s, err1 := currentPlaner.GetAllLocalPathFromDB(context.Background())
	// if err1 != nil {
	// 	return err1, nil
	// }
	//获得当前所有的局部路径
	localPaths, err1 := currentPlaner.GetAllLocalPathFromDB(context.Background())
	if err1 != nil {
		return err1, nil
	}
	dict := make(map[string]model.PathLocks, 0)
	for _, localPath := range localPaths {
		siteLocks := make(model.PathLocks, 0)
		if len(localPath.Paths) > 0 {
			for _, path := range localPath.Paths {
				pathLocks := path.AllBlocks()
				for _, pathLock := range pathLocks {
					siteLocks = append(siteLocks, pathLock)
				}
			}
		}
		for _, specialLock := range localPath.SpecialLocks {
			siteLocks = append(siteLocks, specialLock)
		}
		dict[localPath.Sn] = siteLocks

	}
	//当
	//查找当前车的所有局部路径
	// for _, approved := range allApprovedLocalPath1s {
	// 	if approved.MapName == currentTask.MapName {
	// 		ids := approved.Paths.AllBlocks().ToIds()
	// 		ids = append(ids, approved.SpecialLocks.ToIds()...)
	// 		if robotInArea(ids, limitArea.ContainDotIds) {
	// 			rob := robotmanager.GetFromCache(approved.Sn)
	// 			if rob == nil {
	// 				continue
	// 			}
	// 			if !tools.StringSliceIsContain(groupList, rob.Account.GroupID) {
	// 				continue
	// 			}
	// 			return nil, rob
	// 		}
	// 	}
	// }
	//当前锁定点是否在巷道中
	if len(limitArea.ContainDotIds) > 0 {
		for key, value := range dict {
			if robotInArea(value, limitArea.ContainDotIds) {
				rob := robotmanager.GetFromCache(key)
				if rob == nil {
					continue
				}
				if !tools.StringSliceIsContain(groupList, rob.Account.GroupID) {
					continue
				}
				return nil, rob
			}
		}
	}
	//按照任务地图、agvID不为空 找出还未结束的任务
	tasks, errGetTasks := mc.TM.GetAllHaveAgvIdButUnFinishTasksFromDB(context.Background(), limitRobotAreaContains)
	if errGetTasks != nil {
		log.Panicf("get all unFinish but have agvId tasks error:%v", errGetTasks)
		return errGetTasks, nil
	}
	//找出所有Agv
	for _, task1 := range tasks {
		rob := robotmanager.GetFromCache(task1.AgvId)
		if rob == nil {
			continue
		}
		if !tools.StringSliceIsContain(groupList, rob.Account.GroupID) {
			continue
		}
		return nil, rob
	}

	//判断是否存在车在前瞻点集合中
	if len(limitArea.FrontLookPoints) > 0 {
		for key, value := range dict {
			if robotInArea(value, limitArea.FrontLookPoints) {
				rob := robotmanager.GetFromCache(key)
				if rob == nil {
					continue
				}
				if !tools.StringSliceIsContain(groupList, rob.Account.GroupID) {
					continue
				}
				return nil, rob
			}
		}
	}

	return nil, nil
}

//任务限定区域按照类型区分
func (mc *ManagerCluster) GetRobotInLimitetAreaByRobotType(gotGategoryID int, currentTask model.Task) (codes.Code, *model.Robot) {
	robotInArea := func(ids, ContainDotIds []string) bool {
		for _, id := range ContainDotIds {
			for _, myid := range ids {
				if id == myid {
					return true
				}
			}
		}
		return false
	}
	mapName := currentTask.MapName
	//1.先判断当前任务目标点是否在任务限定区域或者区域的前瞻点中
	currentPlaner := mc.TRM.GetPathPlanner(mapName)
	if currentPlaner == nil {
		return codes.ErrMapPlanerNotFound, nil
	}
	//存在规划器，找出当前目标点所在的限定区域
	limitTaskRobotAreas := currentPlaner.GetCurrentSiteIdContaintFrontArea(currentTask.TargetSiteID, model.AreaTypeTaskLimitRobotArea)
	if limitTaskRobotAreas == nil || len(limitTaskRobotAreas) <= 0 {
		return nil, nil
	}

	//目前只要按照一个区域来算
	limitArea := limitTaskRobotAreas[0]
	limitRobotAreaContains := limitArea.ContainDotIds
	if limitArea.FrontLookPoints != nil && len(limitArea.FrontLookPoints) > 0 {
		limitRobotAreaContains = append(limitRobotAreaContains, limitArea.FrontLookPoints...)
	}
	//获得当前所有的局部路径
	localPaths, err1 := currentPlaner.GetAllLocalPathFromDB(context.Background())
	if err1 != nil {
		return err1, nil
	}

	dict := make(map[string]model.PathLocks, 0)
	for _, localPath := range localPaths {
		siteLocks := make(model.PathLocks, 0)
		if len(localPath.Paths) > 0 {
			for _, path := range localPath.Paths {
				pathLocks := path.AllBlocks()
				for _, pathLock := range pathLocks {
					siteLocks = append(siteLocks, pathLock)
				}
			}
		}
		for _, specialLock := range localPath.SpecialLocks {
			siteLocks = append(siteLocks, specialLock)
		}
		dict[localPath.Sn] = siteLocks

	}
	//当前锁定点是否在巷道中
	for key, value := range dict {
		if robotInArea(value, limitArea.ContainDotIds) {
			rob := robotmanager.GetFromCache(key)
			if rob == nil {
				continue
			}
			if rob.Account.CategoryID != gotGategoryID {
				continue
			}
			return nil, rob
		}
	}
	//判断当前车
	//按照任务地图、agvID不为空 找出还未结束的任务
	tasks, errGetTasks := mc.TM.GetAllHaveAgvIdButUnFinishTasksFromDB(context.Background(), limitRobotAreaContains)
	if errGetTasks != nil {
		log.Panicf("get all unFinish but have agvId tasks error:%v", errGetTasks)
		return errGetTasks, nil
	}
	//找出所有Agv
	for _, task1 := range tasks {
		rob := robotmanager.GetFromCache(task1.AgvId)
		if rob == nil {
			continue
		}
		if rob.Account.CategoryID != gotGategoryID {
			continue
		}
		return nil, rob
	}
	//判断是否存在车在前瞻点集合中
	if len(limitArea.FrontLookPoints) > 0 {
		for key, value := range dict {
			if robotInArea(value, limitArea.FrontLookPoints) {
				rob := robotmanager.GetFromCache(key)
				if rob == nil {
					continue
				}
				if rob.Account.CategoryID != gotGategoryID {
					continue
				}
				return nil, rob
			}
		}
	}

	return nil, nil
}
